<?php
    class iJLanguages
    {
        
        private $langCode;
        private $defaultTokens;
        private $languages;
        private $currentLanguage;
        /**
         *
         * This function is construct Languages
         *
         *
         * @access public
         */
        public function __construct() {
        }
        /**
         *
         * This function returns current language code
         *
         *
         * @access public
         */
        public function getLangCode() {
            return $this->langCode;
        }
        /**
         *
         * This function returns all used languages
         *
         *
         * @access public
         */        
        public function getLanguages() {
            return $this->languages;
        }
        /**
         *
         * This function returns current laguage
         *
         *
         * @access public
         */             
        public function getLanguage() {
            return $this->currentLanguage;
        }
        /**
         *
         * This function returns all languages except current
         *
         *
         * @access public
         */           
        public function getLanguagesExeptCurrent() {
            $lang = $this->languages;
            unset($lang[$this->currentLanguage['id']]);
            return $lang;
        }
        /**
         *
         * This function checks if the current laguage exists
         *
         *
         * @access public
         */                   
        public function isLanguageExists($code) {
            foreach($this->languages as $lang) {
                if($lang['code'] == $code) {
                    return true;
                }
            }
            return false;
        }
        /**
         *
         * This function insterts into database new laguage definition
         *
         *
         * @access public
         */                   
        public function addDefinition($target, $id, $langCode, $definition) {
            if($this->isLanguageExists($langCode)) {
                $iJDataBase =  iJFactory::singleton('iJDataBase');
                $Qlang = $iJDataBase->query('INSERT INTO :table_language_definitions
                                                        (
                                                            tableName,
                                                            rowID,
                                                            langCode,
                                                            value
                                                        )
                                                        VALUES 
                                                        (
                                                            :tableName,
                                                            :rowID,
                                                            :langCode,
                                                            :value
                                                        )
                                            ON DUPLICATE KEY UPDATE 
                                            value = :value
                                            ');
                $Qlang->bindTable(':table_language_definitions', TABLE_LANGUAGES_DEFINITIONS);
                
                $Qlang->bindValue(':tableName', $target);
                $Qlang->bindValue(':rowID',     $id);
                $Qlang->bindValue(':langCode', $langCode);
                $Qlang->bindValue(':value',    $definition);
                $Qlang->execute();
            }
        }
        /**
         *
         * This function returns all values in laguage table in database
         *
         *
         * @access public
         */          
        public function getDefinition($target, $id, $langCode = '') {
          if($langCode == '') {
            $langCode = $this->langCode;
          }
          if($this->isLanguageExists($langCode)) {
              $iJDataBase =  iJFactory::singleton('iJDataBase');
              $Qlang = $iJDataBase->query('SELECT 
                                            value 
                                          FROM  :table_language_definitions
                                          WHERE tableName = :tableName 
                                            AND rowID     = :rowID
                                            AND langCode  = :langCode
                                         ');
              $Qlang->bindTable(':table_language_definitions', TABLE_LANGUAGES_DEFINITIONS);
              
              $Qlang->bindValue(':tableName', $target);
              $Qlang->bindValue(':rowID',     $id);
              $Qlang->bindValue(':langCode', $langCode);
              $Qlang->execute();
              if($Qlang->next()) {
                return $Qlang->value('value');
              } else {
                return NULL;
              }
          }
      }
        /**
         *
         * This function returns all values in laguage table in database
         *
         *
         * @access public
         */          
      public function removeDefinitions($target, $id) {
          $iJDataBase =  iJFactory::singleton('iJDataBase');
          $Qlang = $iJDataBase->query('DELETE FROM :table_language_definitions
                                      WHERE tableName = :tableName AND rowID = :rowID AND (');
          $term = '';
          foreach($this->languages as $lang) {
             $Qlang->appendQuery($term . 'langCode = :langCode'); 
             $Qlang->bindValue(':langCode', $lang['code']);
             $term = ' OR ';
          }
          $Qlang->appendQuery(')'); 
          
          $Qlang->bindTable(':table_language_definitions', TABLE_LANGUAGES_DEFINITIONS);
          $Qlang->bindValue(':tableName', $target);
          $Qlang->bindValue(':rowID',     $id);
          $Qlang->execute();       
        }
        
        public function init() {

            
            if(!isset($_COOKIE['lang'])) {
                $cookieExpireDate = time() + COOKIES_LIFE_TIME*3600;
                setcookie('lang', DEFAULT_LANG_CODE, $cookieExpireDate, '/');
                $this->langCode = DEFAULT_LANG_CODE;
            } else {
                $this->langCode = $_COOKIE['lang'];
            }
            
            if(isset($_POST['langCode'])) {
               $this->langCode = $_POST['langCode'];
               $cookieExpireDate = time() + COOKIES_LIFE_TIME*3600;
               setcookie('lang', $this->langCode, $cookieExpireDate, '/');
            }
            
            $iJDataBase =  iJFactory::singleton('iJDataBase');
            $Qlang = $iJDataBase->query('SELECT * FROM :table_languages');
            $Qlang->bindTable(':table_languages', TABLE_LANGUAGES);
            $Qlang->execute();
            while($Qlang->next()) {
                $lang[$Qlang->value('id')]['id']       = $Qlang->value('id');             
                $lang[$Qlang->value('id')]['code']     = $Qlang->value('code');
                $lang[$Qlang->value('id')]['icon']     = WORLD_FLAGS . $Qlang->value('code') . '.png';
                $lang[$Qlang->value('id')]['language'] = $Qlang->value('language');
                
                if($lang[$Qlang->value('id')]['code'] == $this->langCode) {
                    $current['id']       = $lang[$Qlang->value('id')]['id'];    
                    $current['code']     = $lang[$Qlang->value('id')]['code'];
                    $current['icon']     = $lang[$Qlang->value('id')]['icon'];
                    $current['language'] = $lang[$Qlang->value('id')]['language'];
                }
                
                //TODO error report
                if(isset($current)) {
                    $this->currentLanguage = $current;
                } else {
                    $this->currentLanguage = NULL;
                }
                
                $this->languages = $lang;
            }
            $this->loadDefaultTokens();
            
        }
        
       
        /**
         *
         * Loads defaul languages tockens
         *
         * @return array Array with the tokens of the block
         *
         * @access public
         */
        
        private function loadDefaultTokens() {
            $lang = iJEngineXML::getArrayFromXMLFile(DIR_BACKEND_LANGUAGES . $this->getLangCode() . '/' . DEFAULT_LANGUAGE_FILE);
            $blockLanguageTokens = array();
            if(empty($lang['language']['definition'])) {
                return;
            }
       
            foreach($lang['language']['definition'] as $definition) {
                $blockLanguageTokens[$definition['key']]  = $definition['value'];
                

            }
            $this->defaultTokens =  $blockLanguageTokens;
         }
        
        public function getDefaultTokens() {
            return $this->defaultTokens;
        }
        
        public function load($xmlFileName) {
          $lang = iJEngineXML::getArrayFromXMLFile(DIR_BACKEND_LANGUAGES . $this->getLangCode() . '/' . $xmlFileName);
          $languageTokens = array();
          if(empty($lang['language']['definition'])) {
              return;
          }
     
          foreach($lang['language']['definition'] as $definition) {
              $languageTokens[$definition['key']]  = $definition['value'];
              

          }
          $this->defaultTokens = array_merge($this->defaultTokens, $languageTokens);
        }
        
        public function getTocken($name) {
            if(isset($this->defaultTokens[$name])) {
                return $this->defaultTokens[$name];
            } else {
                return $name;
            }
            
        }

        /**
         *
         * Gets all languge
         *
         * @return array Array with the tokens of the block
         *
         * @access public
         */        
        public function getLanguageList($page, $search, $limit = '') {
          $iJDataBase =  iJFactory::singleton('iJDataBase');
          $iJDataBaseTok =  iJFactory::singleton('iJDataBase');
          
          $Qlang = $iJDataBase->query('SELECT   id, 
                                               language,
                                               code
                                        FROM :table_lang');
          $Qlang->bindTable(':table_lang', TABLE_LANGUAGES);
          
          
          
          if(!empty($search)) {
            $Qlang->appendQuery('where code like :search OR language like :search');
            $Qlang->bindValue(':search', '%' . $search . '%');
          }
          $Qlang->appendQuery(':limit');
          $Qlang->bindTable(':limit', $Qlang->addLimit($page, $limit));
          $Qlang->execute();
          
          $languages = array();
          while($Qlang->next()) {
              $language['id']          =  $Qlang->value('id');
              $language['language']    =  $Qlang->value('language');
              $language['code']        =  $Qlang->value('code');
              $language['trash']       = '' ;//xHrefLink::linkToLocalPage('admin_blocks') . '?delID=' . $language['id'];
              $language['icon']        = WORLD_FLAGS . $Qlang->value('code') . '.png';
              $language['count']       = 0;
              
              $QTok = $iJDataBaseTok->query("SELECT COUNT(*) count
                                          FROM  :table_lang_definitions
                                          WHERE langCode = :code ");
              $QTok->bindTable(':table_lang_definitions', TABLE_LANGUAGES_DEFINITIONS);
              $QTok->bindValue(':code',  $language['code']);
              $QTok->execute();
              if($QTok->next()) {
                $language['count'] = $language['count'] + $QTok->value('count');
              }
              $language['count'] = $language['count'] + $this->getTockensCount($language['code'] );
              $languages[] =  $language;
              
          }
          return array($languages, $Qlang);
          
        }
        
        public function getTockensCount($langCode){
          $count = 0;
          $langFiles = iJScanDir(DIR_BACKEND_LANGUAGES . $langCode);
          foreach($langFiles as $file) {
            $lang = iJEngineXML::getArrayFromXMLFile($file);
            if(empty($lang['language']['definition'])) {
              continue;
            }
            $count = $count + count($lang['language']['definition']);
          }
          return $count;
        }
        
        public function trashTocken($blockId, $key) {          
           $iJLanguages = iJFactory::singleton('iJLanguages');
           $block_info = iJBlock::getBlockInfo($blockId);
           $langTokens = array();
           if(isset($block_info['language']) && !empty($block_info['language']))  {
              $path = '';              
              if($block_info['isAdmin'] == 1) {
                  $path    = DIR_BACKEND_LANGUAGES;                  
              } else {
                  $path    = DIR_FRONTEND_LANGUAGES;                  
              }              
              $languages = $iJLanguages->getLanguages();
              $keys = array();
              foreach($languages as $lang) {                
                $langTokens = iJEngineXML::getArrayFromXMLFile($path . $lang['code'] . '/' . $block_info['language']);
                   
                if(isset($langTokens['language']['definition']['key'])) {
                  $def = $langTokens['language']['definition'];
                  unset($langTokens['language']['definition']);
                  $langTokens['language']['definition'][0] = $def;
                }
            
                if(empty($langTokens['language']['definition'])) {
                     continue;
                }
                                    
                foreach($langTokens['language']['definition'] as $fileKey => $fileTocken) {
                  if($fileTocken['key'] == $key)
                    unset($langTokens['language']['definition'][$fileKey]);                                      
                }
                if(!isset($langTokens['language']['definition'][0])) {
                  $langTokens['language']['definition'][0] = $langTokens['language']['definition'][1]; 
                } 
                $xml = iJEngineXML::toXML($langTokens);                
                $fh  = fopen($path . $lang['code'] . '/' . $block_info['language'],"w+");
                fwrite($fh, $xml);
                fclose($fh);                                                                                 
              }                            
              
          }
          iJMessages::display('success', 'deleted');          
       }
       
        public static function saveTockens($key, $mas, $blockId){
          
           $iJLanguages = iJFactory::singleton('iJLanguages');
           $block_info = iJBlock::getBlockInfo($blockId);           
           $langTokens = array();           
           if(isset($block_info['language']) && !empty($block_info['language']))  {            
              $path = '';              
              if($block_info['isAdmin'] == 1) {                
                  $path    = DIR_BACKEND_LANGUAGES;                  
              } else {                
                  $path    = DIR_FRONTEND_LANGUAGES;                  
              }                            
              $languages = $iJLanguages->getLanguages();              
              $keys = array();
              $mas = cleanUpArray($mas);
              foreach($languages as $lang) {
                if(!file_exists($path . $lang['code'] . '/' . $block_info['language'])) {
                  $fh  = fopen($path . $lang['code'] . '/' . $block_info['language'], "w+");
                  $new['key']   = $key;
                  $new['value'] = $mas[$lang['code']];
                  $langTokensNew['language']['definition'][] = $new;
                  $xmlNew = iJEngineXML::toXML($langTokensNew);
                  fwrite($fh, $xmlNew);
                  fclose($fh);
                  break;
                }
                $langTokens = iJEngineXML::getArrayFromXMLFile($path . $lang['code'] . '/' . $block_info['language']);
                   
                if(isset($langTokens['language']['definition']['key'])) {                  
                  $def = $langTokens['language']['definition'];
                  unset($langTokens['language']['definition']);
                  $langTokens['language']['definition'][0] = $def;
                }
            
                if(empty($langTokens['language']['definition'])) {                  
                     continue;
                }
                $flag = true;                                                  
                foreach($langTokens['language']['definition'] as $fileKey => $fileTocken) {                  
                  
                  if($fileTocken['key'] == $key){                                          
                     $langTokens['language']['definition'][$fileKey]['value'] = $mas[$lang['code']];
                     $flag = false;                     
                  }
                                       
                                                                  
                }                                              
                if ($flag) {
                  $n['key']   = $key;
                  $n['value'] = $mas[$lang['code']];
                  $langTokens['language']['definition'][] = $n;
                }
                $xml = iJEngineXML::toXML($langTokens);                
                $fh  = fopen($path . $lang['code'] . '/' . $block_info['language'],"w+");                
                fwrite($fh, $xml);                
                fclose($fh);                                                                                               
              }                            
              
          }
          return iJMessages::ajaxDisplay('success','lang_token_saved');          
                       
        }
        
        public static function newTockens($key, $mas, $blockId, $page){
                      
           //iJDebug::log($mas);           
                   
           $iJLanguages = iJFactory::singleton('iJLanguages');
           $block_info = iJBlock::getBlockInfo($blockId);           
           $langTokens = array();           
           if(isset($block_info['language']) && !empty($block_info['language']))  {            
              $path = '';              
              if($block_info['isAdmin'] == 1) {                
                  $path    = DIR_BACKEND_LANGUAGES;                  
              } else {                
                  $path    = DIR_FRONTEND_LANGUAGES;                  
              }                            
              $languages = $iJLanguages->getLanguages();              
              $keys = array();
              $mas = cleanUpArray($mas);
              foreach($languages as $lang) {
                if(!file_exists($path . $lang['code'] . '/' . $block_info['language'])) {
                  $fh  = fopen($path . $lang['code'] . '/' . $block_info['language'], "w+");
                  $new['key']   = $key;
                  $new['value'] = $mas[$lang['code']];
                  $langTokensNew['language']['definition'][] = $new;
                  $xmlNew = iJEngineXML::toXML($langTokensNew);
                  fwrite($fh, $xmlNew);
                  fclose($fh);
                  break;
                }
                $langTokens = iJEngineXML::getArrayFromXMLFile($path . $lang['code'] . '/' . $block_info['language']);
                   
                if(isset($langTokens['language']['definition']['key'])) {                  
                  $def = $langTokens['language']['definition'];
                  unset($langTokens['language']['definition']);
                  $langTokens['language']['definition'][0] = $def;
                }
            
                if(empty($langTokens['language']['definition'])) {                  
                     continue;
                }
                //$flag = true;                                                  
                //foreach($langTokens['language']['definition'] as $fileKey => $fileTocken) {                  
                  $n['key']   = $key;
                  //xDebug::log($mas[$lang['code']]);
                  $n['value'] = $mas[$lang['code']];
                  //$langTokens['language']['definition'][] = $n;                                                                                                                           
                //}
                $tmp = array();
                $i = 1;
                $tmp[0] =  $n;
                foreach($langTokens['language']['definition'] as $token) {
                  $tmp[$i] = $token;
                  $i++;
                }                 
                $langTokens['language']['definition'] = $tmp;                                                                                                           
                $xml = iJEngineXML::toXML($langTokens);                
                $fh  = fopen($path . $lang['code'] . '/' . $block_info['language'],"w+");                
                fwrite($fh, $xml);                
                fclose($fh);                                                                                               
              }                            
              
          }          
          $data['message'] = iJMessages::ajaxDisplay('success','lang_token_saved');
          $data['trash']   = iJHrefLink::linkToLocalPage('language_editor') .'?blockID=' . $blockId . '&page=' . trim($page) . '&trash=' . $key;
          return $data;   
        }                 
    }
?>